package com.visionork.android.tai.model.adapter;

import java.net.URL;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.visionork.android.tai.model.Program;
import com.visionork.android.tai.model.ProgramType;

public class DramaProgramAdapter extends TaiAdapterBase {
	private static final String PREFIX = "http://sugoideas.com";
	private static final int[] years = {2011, 2010, 2009, 2008, 2007, 2006, 2005, 2004, 2003, 2002, 2001};
	public DramaProgramAdapter(String urlLink) {
		super(urlLink);
	}

	@Override
	public ArrayList<?> getData() {
		ArrayList<Program> programs = new ArrayList<Program>();
		for(int year : years)
		{
			String yearUrlLink = String.format("http://sugoideas.com/search/%ddrama", year);
			programs.addAll(parseUrl(yearUrlLink, year));
		}
		
		return programs;
	}
	
	private ArrayList<Program> parseUrl(String yearUrlLink, int year) {
		ArrayList<Program> programs = new ArrayList<Program>();
		try {
			Document doc = Jsoup.parse(new URL(yearUrlLink), TIME_OUT);
			Elements elms = doc.getElementsByTag("div");
			for (Element elm : elms) {
				if (elm.hasAttr("class")
						&& elm.attr("class").equals("postsearch")) {
					Program program = parseProgram(elm, year);
					if (program != null) {
						programs.add(program);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return programs;
	}
	private Program parseProgram(Element elm, int year) {
		String title = null;
		String urlLink = null;
		String hosts = null;
		Elements hrefElms = elm.getElementsByTag("a");
		if (hrefElms != null && hrefElms.size() == 1) {
			Elements imgElms = hrefElms.get(0).getElementsByTag("img");
			if (imgElms != null && imgElms.size() == 1) {

				title = imgElms.get(0).attr("title");
				String[] stringParts = title.split("/");
				title = stringParts[stringParts.length - 1].trim();
				urlLink = hrefElms.get(0).attr("href");

			}
		}

		Elements hostElms = elm.getElementsByTag("span");
		for (Element hostElm : hostElms) {
			if (hostElm.hasAttr("class")
					&& hostElm.attr("class").equals("searchOne"))

			{
				hosts = hostElm.text().trim();
				break;
			}
		}

		if (urlLink != null && title != null && urlLink.startsWith(PREFIX)
				&& title.trim().length() > 0) {
			Program prog = new Program();
			prog.setTitle(String.format("%s (%d)", title, year));
			prog.setUrlLink(urlLink);
			prog.setProgramType(ProgramType.Drama);
			prog.setMeta(hosts);
			
			return prog;
		}

		return null;
	}
}
